<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>多用户任务监控面板</title>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
            color: #333;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        h1 {
            color: #2c3e50;
            text-align: center;
            margin-bottom: 30px;
        }
        .control-panel {
            display: flex;
            justify-content: space-between;
            margin-bottom: 20px;
            align-items: center;
        }
        .refresh-btn {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
        }
        .refresh-btn:hover {
            background-color: #2980b9;
        }
        .search-box {
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            width: 300px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        th, td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        th {
            background-color: #f2f2f2;
            font-weight: bold;
            position: sticky;
            top: 0;
        }
        tr:hover {
            background-color: #f9f9f9;
        }
        .status {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: bold;
        }
        .status-running {
            background-color: #f39c12;
            color: white;
        }
        .status-success {
            background-color: #2ecc71;
            color: white;
        }
        .status-failed {
            background-color: #e74c3c;
            color: white;
        }
        .last-updated {
            text-align: right;
            font-size: 12px;
            color: #7f8c8d;
            margin-top: 10px;
        }
        .user-badge {
            background-color: #9b59b6;
            color: white;
            padding: 3px 8px;
            border-radius: 12px;
            font-size: 12px;
            margin-right: 5px;
        }
        .action-btn {
            padding: 5px 10px;
            border: none;
            border-radius: 3px;
            cursor: pointer;
            margin-right: 5px;
        }
        .cancel-btn {
            background-color: #e74c3c;
            color: white;
        }
        .detail-btn {
            background-color: #3498db;
            color: white;
        }
    </style>
</head>
<body>
<div class="container">
    <h1>多用户任务监控面板</h1>

    <div class="control-panel">
        <div>
            <input type="text" class="search-box" placeholder="搜索用户或商品..." onkeyup="filterTasks()">
        </div>
        <button class="refresh-btn" onclick="fetchData()">
            <span id="refreshIcon">⟳</span> 刷新数据
        </button>
    </div>

    <div id="lastUpdated" class="last-updated">最后更新时间: 未更新</div>

    <div id="taskTableContainer">
        <table>
            <thead>
            <tr>
                <th>用户</th>
                <th>任务ID</th>
                <th>商品名称</th>
                <th>心理价位</th>
                <th>子类型</th>
                <th>状态</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody id="taskTableBody">
            <!-- 数据将通过JavaScript动态填充 -->
            </tbody>
        </table>
    </div>
</div>

<script>
    // Configuration
    const config = {
        baseUrl: 'http://47.109.35.232:7779',
        wsUrl: 'ws://47.109.35.232:7779/websocket/logging',
        //baseUrl: 'http://localhost:7779',
        //wsUrl: 'ws://localhost:7779/websocket/logging',
        refreshInterval: 2000,
        toastDuration: 3000,
        logLimit: 1000 // Maximum number of log entries to keep
    };
    // 示例数据 - 实际使用时将从API获取
    const sampleData = {
        "TJB": [{
            "userName": "TJB",
            "heartPrice": "100",
            "goodName": "九鹿图",
            "subType": "34839",
            "taskId": "http-nio-7779-exec-2",
            "status": "running"
        }],
        "TQ": [{
            "userName": "TQ",
            "heartPrice": "100",
            "goodName": "九鹿图",
            "subType": "34839",
            "taskId": "http-nio-7779-exec-3",
            "status": "running"
        }],
        "HJY": [{
            "userName": "TQ",
            "heartPrice": "100",
            "goodName": "九鹿图",
            "subType": "34839",
            "taskId": "http-nio-7779-exec-3",
            "status": "running"
        }]
    };

    // 页面加载时获取数据
    document.addEventListener('DOMContentLoaded', function() {
        fetchData();
        // 每30秒自动刷新一次
        setInterval(fetchData, 30000);
    });

    // 获取数据并更新界面
    function fetchData() {
        // 旋转刷新图标
        const icon = document.getElementById('refreshIcon');
        icon.style.transform = 'rotate(360deg)';
        icon.style.transition = 'transform 0.5s ease';

        setTimeout(() => {
            icon.style.transform = 'rotate(0deg)';
        }, 500);

        fetch(`${config.baseUrl}/getRunningTasks`)
            .then(response => response.json())
            .then(data => {
                updateUI(data)
            })
            .catch(error => {
                console.error('Error fetching task count:', error);
            });
    }

    // 更新界面
    function updateUI(data) {
        const taskTableBody = document.getElementById('taskTableBody');
        //清空
        taskTableBody.innerHTML = '';
        taskTableBody.replaceChildren()
        // 更新最后更新时间
        document.getElementById('lastUpdated').textContent =
            `最后更新时间: ${new Date().toLocaleString()}`;

        // 遍历所有用户的任务
        for (const [userName, tasks] of Object.entries(data)) {
            tasks.forEach(task => {
                const row = document.createElement('tr');

                // 根据状态设置CSS类
                const statusClass = `status-${task.status || 'running'}`;
                const statusText = {
                    'running': '运行中',
                    'success': '成功',
                    'failed': '失败'
                }[task.status || 'running'];

                row.innerHTML = `
                        <td><span class="user-badge">${task.userName}</span></td>
                        <td>${task.taskId}</td>
                        <td>${task.goodName}</td>
                        <td>${task.heartPrice}</td>
                        <td>${task.subType}</td>
                        <td><span class="status ${statusClass}">${statusText}</span></td>
                        <td>
                            <button id="btn-cancel" class="action-btn cancel-btn" onclick="cancelTask('${task.userName}', '${task.taskId}')">取消</button>
                        </td>
                    `;
                taskTableBody.appendChild(row);
            });
        }
    }

    // 搜索/过滤功能
    function filterTasks() {
        const input = document.querySelector('.search-box');
        const filter = input.value.toUpperCase();
        const rows = document.querySelectorAll('#taskTableBody tr');

        rows.forEach(row => {
            const text = row.textContent.toUpperCase();
            row.style.display = text.includes(filter) ? '' : 'none';
        });
    }

    // 显示任务详情
    function showDetail(userName, taskId) {
        alert(`查看详情:\n用户: ${userName}\n任务ID: ${taskId}`);
        // 实际应用中这里可以打开模态框或跳转到详情页
    }

    // 取消任务函数
    function cancelTask(userName, taskId) {
        if (confirm(`确定要取消用户 ${userName} 的任务 ${taskId} 吗?`)) {
            // 这里添加取消任务的API调用
            fetch(`${config.baseUrl}/cancelTaskByName?userName=${encodeURIComponent(userName)}&taskId=${encodeURIComponent(taskId)}`)
                .then(response => response.json())
                .then(data => {
                    if (data === 200){
                        document.querySelectorAll('#taskTableBody tr').forEach(row => {
                            if (row.cells[1].textContent === taskId) {
                                row.cells[5].innerHTML = '<span class="status status-failed">已取消</span>';
                            }
                        });
                    }else{
                        alert("取消失败");
                    }
                })
                .catch(error => {
                    console.error('Error fetching task count:', error);
                });
        }
    }
</script>
</body>
</html>